package top.jacktgq.itheima.bio.UDP.Demo2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/*
 * 实现UDP接收端
 * 永不停歇的接收端
 */
public class UDPReceive {

	public static void main(String[] args) {
		try {
			
			//创建数据包传输对象DatagramSocket绑定端口号
			DatagramSocket ds = new DatagramSocket(5000);
			
			while (true) {
				//创建一个字节数组等着装数据
				byte[] data = new byte[1024];
				//创建数据包对象，传递字节数组
				DatagramPacket dp = new DatagramPacket(data, data.length);
				//调用ds对象的方法receive传递数据包
				ds.receive(dp);
				//获取发送端的IP地址对象
				String ip = dp.getAddress().getHostAddress();
				//获取接收到的字节个数
				int length = dp.getLength();
				//获取发送端的端口号
				int port = dp.getPort();
				//数据发送端IP地址和发送数据
				System.out.println(ip + "-" + port + "：" + new String(data, 0, length));
			}
			
			//关闭资源
			//ds.close();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
